import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:intl/intl.dart';

import 'package:mobile_vpn/common/cpn/cpn_view_state.dart';
import 'package:mobile_vpn/common/cpn/sliver_app_bar.dart';
import 'package:mobile_vpn/pages/user_page/user_login.dart';
import '../../router/routers.dart';
import '../../theme/color_palettes.dart';
  class UserPage extends CpnViewState<UserLogic> {

  UserPage({Key? key}) : super(key: key, bindViewState: false);
  BuildContext? _context;
  final List<Device> mockDevices = [
    Device(
      id: '441402618',
      name: 'Primary Phone',
      type: '智能手机',
      os: 'Android 15',
      lastActive: DateTime(2025, 3, 31, 14, 30),
      isCurrentDevice: true, // 标记本机设备
    ),
    Device(
      id: '758203946',
      name: 'Work Tablet',
      type: '平板电脑',
      os: 'iPadOS 19',
      lastActive: DateTime(2025, 3, 28, 9, 15),
    ),
    Device(
      id: '692471385',
      name: 'Backup Device',
      type: '智能手机',
      os: 'iOS 19',
      lastActive: DateTime(2025, 2, 15, 18, 42),
    ),
    Device(
      id: '325809167',
      name: 'Media Center',
      type: '智能电视',
      os: 'Android TV 14',
      lastActive: DateTime(2024, 12, 25, 20, 0),
    ),
  ];

  @override
  Widget buildBody(BuildContext context) {
    _context = context;
    return Scaffold(
      backgroundColor: ColorPalettes.instance.background,
      body: CustomScrollView(
        slivers: <Widget>[
          commonSliverAppBar(
            title: '我的账户',
            action: [
              Icon(Icons.settings,
                  color: ColorPalettes.instance.firstText,  size: 36.w)
            ],
            actionClick: [
                  () {
                AppRoutes.jumpPage(AppRoutes.userSetPage);
              }
            ],
          ),
          SliverToBoxAdapter(
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal:  20.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 30.h),
                  // 用户头像和信息
                  _buildUserProfile(),
                  SizedBox(height: 30.h),
                  // 设备管理
                  _buildDeviceManagement(),
                  SizedBox(height: 30.h),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserProfile() {
    return Card(
      elevation: 4,
      color: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Padding(
        padding: EdgeInsets.zero,
        child: Column(
          children: [
            Row(
              children: [
                Padding(
                  padding: EdgeInsets.only(left:  60.w), // 设置头像距离左边的距离
                  child: Stack(
                    children: [
                      CircleAvatar(
                        radius: 80.r, // 调整头像大小
                        // backgroundImage: AssetImage('assets/profile_placeholder.png'),
                      ),
                      Positioned(
                        bottom: 0,
                        left: 0,
                        right: 0,
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              vertical: 8.h, horizontal: 16.w), // 调整内边距
                          decoration: BoxDecoration(
                            color: Colors.grey,
                            borderRadius: BorderRadius.vertical(
                                bottom: Radius.circular(80.r)),  // 调整圆角
                          ),
                          child: Text(
                            '已过期',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 32.sp,  // 调整字体大小
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(width: 30.w, height: 200.h),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'wangningning123',
                        style: TextStyle(
                          fontSize: 32.sp,
                          fontWeight: FontWeight.bold,
                          color: ColorPalettes.instance.firstText,
                        ),
                      ),
                      SizedBox(height: 12.h),
                      Row(
                        children: [
                          Text(
                            '会员剩余时间：',
                            style: TextStyle(
                              fontSize: 28.sp,
                              color: ColorPalettes.instance.secondText,
                            ),
                          ),
                          SizedBox(width: 10.w),
                          Text(
                            '0分钟',
                            style: TextStyle(
                              fontSize: 28.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),

          ],
        ),
      ),
    );
  }

  Widget _buildDeviceList() {
    return ListView.separated(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemCount: mockDevices.length,
      separatorBuilder: (_, __) => SizedBox(height: 12.h),
      itemBuilder: (context, index) {
        final device = mockDevices[index];
        return _buildDeviceCard(device);
      },
    );
  }

  Widget _buildDeviceCard(Device device) {
    return Card(
      margin: EdgeInsets.only(bottom:  12.h),
      color: Colors.white,
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  _getDeviceIcon(device.type),
                  size: 50.w,
                  color: ColorPalettes.instance.primary,
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: Text(
                    device.name,
                    style: TextStyle(
                      fontSize: 32.sp,
                      fontWeight: FontWeight.bold,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                if (device.isCurrentDevice)
                  Container(
                    margin: EdgeInsets.only(left:  8.w),
                    padding:
                    EdgeInsets.symmetric(horizontal:  10.w, vertical: 2.h),
                    decoration: BoxDecoration(
                      color: Colors.green[100],
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    child: Text(
                      '本机设备',
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: Colors.green[800],
                      ),
                    ),
                  )
              ],
            ),
            SizedBox(height: 12.h),
            _buildDetailRow('设备类型：', device.type),
            _buildDetailRow('操作系统：', device.os),
            _buildDetailRow('最后活跃：',
                DateFormat('yyyy-MM-dd HH:mm').format(device.lastActive)),
            SizedBox(height: 8.h),
            if (!device.isCurrentDevice)
              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  child: Text('移除此设备', style: TextStyle(color: Colors.red)),
                  onPressed: () => _showDeleteConfirmDialog(
                      _context!,
                      Device(
                        id: '441402618',
                        name: 'Primary Phone',
                        type: '智能手机',
                        os: 'Android 15',
                        lastActive: DateTime(2025, 3, 31, 14, 30),
                        isCurrentDevice: true, // 标记本机设备
                      )),
                ),
              ),
          ],
        ),
      ),
    );
  }

  void _showDeleteConfirmDialog(BuildContext context, Device device) {
    print('object');
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('确认移除设备'),
          content: Text('确定要移除设备 "${device.name}"   吗？此操作不可撤销。'),
          actions: <Widget>[
            TextButton(
              child: Text('取消',
                  style: TextStyle(color: ColorPalettes.instance.secondText)),
              onPressed: () => Navigator.of(context).pop(),
            ),
            TextButton(
              child: Text('确认移除', style: TextStyle(color: Colors.red)),
              onPressed: () {
                // 这里可以添加实际的移除逻辑
                // 例如：controller.removeDevice(device.id);
                Navigator.of(context).pop();
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Text('设备 "${device.name}"   已移除'),
                    duration: Duration(seconds: 2),
                  ),
                );
              },
            ),
          ],
        );
      },
    );
  }

  IconData _getDeviceIcon(String type) {
    switch (type) {
      case '智能手机':
        return Icons.smartphone;
      case '平板电脑':
        return Icons.tablet_android;
      case '智能电视':
        return Icons.tv;
      default:
        return Icons.devices_other;
    }
  }

  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical:  4.h),
      child: RichText(
        text: TextSpan(
          style: TextStyle(
            fontSize: 28.sp,
            color: ColorPalettes.instance.secondText,
          ),
          children: [
            TextSpan(
                text: label, style: TextStyle(fontWeight: FontWeight.bold)),
            TextSpan(text: value),
          ],
        ),
      ),
    );
  }

  Widget _buildDeviceManagement() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '设备管理 (${mockDevices.length}   台)',
          style: TextStyle(
            fontSize: 32.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 16.h),
        _buildDeviceList(),
      ],
    );
  }
}

class Device {
  final String id;
  final String name;
  final String type;
  final String os;
  final DateTime lastActive;
  final bool isCurrentDevice;

  Device({
    required this.id,
    required this.name,
    required this.type,
    required this.os,
    required this.lastActive,
    this.isCurrentDevice  = false,
  });
}